// 我是约定@umijs/plugin-model写法、可以写很多全局状态管理
import { useCallback } from 'react';
import { useLocalStorageState } from 'ahooks';
import { LocalStorageName, LocalStorageTokenName } from '@/utils/localStorageModel';

export declare type useUserModelType = {
  /**
   * 用户信息
   */
  user: any;
  /**
   * token信息
   */
  token: any;
  /**
   * 更新用户数据或者toekn数据
   */
  updateUser: (userInfo?: any, userToken?: string) => any;
  /**
   * 清空用户信息
   *
   */
  clearUser: () => void;
};

export default function useUserModel(): useUserModelType {
  const [user, setUser] = useLocalStorageState<any>(LocalStorageName, {
    defaultValue: null,
  });
  const [token, setToken] = useLocalStorageState<any>(LocalStorageTokenName, {
    defaultValue: null,
  });

  const updateUser = useCallback(async (userInfo?: any, userToken?: string) => {
    if (userInfo) {
      setUser(userInfo);
    }
    if (userToken) {
      setToken(userToken);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const clearUser = useCallback(() => {
    setUser(undefined);
    setToken(undefined);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return {
    user,
    token,
    updateUser,
    clearUser,
  };
}
